const Service = require("egg").Service;
const jwt = require("jsonwebtoken");
let token = null;
let time = null;
class AgentUserService extends Service {
    async getVerification() {
        const { ctx } = this;
        const { tel } = ctx.request.body;
        let verification = Math.random().toString().slice(2, 8);
        token = jwt.sign(tel, verification);
        time = Date.now();
        return {
            verification
        }
    }
    async login() {
        const { ctx, app } = this;
        const { tel, verification } = ctx.request.body;
        const item = await app.mysql.get("userAgents", { tel: tel });
        //判断是否被禁用
        if (item !== null && !item?.Enable) return "账号已经被禁用"
        try {
            let is = tel === jwt.verify(token, verification);
            console.log(verification, is, tel);
            if (time + (70 * 1000) > Date.now()) {
                if (is) {
                    if (!item) {
                        await app.mysql.insert("userAgents", { username: tel, tel: tel, nickname: "用户" + tel });
                        item = await app.mysql.get({ tel });
                    }
                    return {
                        token: jwt.sign(JSON.stringify(item), ctx.app.config.keys),
                        userData: item
                    }
                } else {
                    return "请不要更改手机号";
                }
            } else {
                return "验证码过期"
            }
        } catch (err) {
            console.log(err);
            return "登录失败,验证码错误";
        }
    }

}
module.exports = AgentUserService;